<template>

  <div class="currentBox">
    <!-- 头部 -->
    <div class="topPart">
      <div class="backBtn" @click="backToHome()">  <svg-icon class-name="back-icon" icon-class="back" /><span>返回</span></div>
      <div class="topMainTitle">实时课堂行为查看</div>
      <div v-if="start" class="topRight">
        <span>采样间隔：{{ currentTask.sampling_interval }}秒</span>
        <timePart />
      </div>
    </div>
    <!-- 课程信息 -->
    <div v-if="start" class="classBtnLine">
      <div class="classInfoBtn">班级：{{ className }}</div>
      <div class="classInfoBtn">任务名称：{{ taskName }}</div>
      <!--  <div class="classInfoBtn">课程：语文</div> -->
      <div class="classInfoBtn">学生：{{ usersInfo.total }}人</div>
    </div>
    <!-- 主要模块 -->
    <div v-if="start" class="mainPart" :class="{ 'mainPart2': !this.$ATTENDANCE }">
      <div class="videoPart" :class="{ 'videoPart2': !this.$ATTENDANCE }">
        <div class="videoPart-tab">
          <button :class="{ active: activeTab === 'student' }" @click="switchTab('student')">学生</button>
          <button :class="{ active: activeTab === 'teacher' }" @click="switchTab('teacher')">老师</button>
        </div>

        <video id="jswebrtc-player" ref="player" width="100%" height="100%" controls />
      </div>


      <div class="actionData">
        <div class="actionOnePart actionOnePart-border">
          <!-- 书写 -->
          <div class="actionOne">
            <div class="actionTitle">书写</div>
            <div class="actionBar">
              <el-progress :percentage="Percent(actionData.write)" :stroke-width="20" :color="colorList[0]" />
            </div>
            <div class="actionNum"><span>{{ actionData.write }}</span><span>{{ Percent(actionData.write) }}%</span></div>
          </div>
          <!-- 阅读 -->
          <div class="actionOne">
            <div class="actionTitle">阅读</div>
            <div class="actionBar">
              <el-progress :percentage="Percent(actionData.read)" :stroke-width="20" :color="colorList[1]" />
            </div>
            <div class="actionNum"><span>{{ actionData.read }}</span><span>{{ Percent(actionData.read) }}%</span></div>
          </div>
          <!-- 听讲 -->
          <div class="actionOne">
            <div class="actionTitle">听讲</div>
            <div class="actionBar">
              <el-progress :percentage="Percent(actionData.listen)" :stroke-width="20" :color="colorList[2]" />
            </div>
            <div class="actionNum"><span>{{ actionData.listen }}</span><span>{{ Percent(actionData.listen) }}%</span></div>
          </div>
          <!-- 转头 -->
          <div class="actionOne">
            <div class="actionTitle">转头</div>
            <div class="actionBar">
              <el-progress :percentage="Percent(actionData.turn)" :stroke-width="20" :color="colorList[3]" />
            </div>
            <div class="actionNum"><span>{{ actionData.turn }}</span><span>{{ Percent(actionData.turn) }}%</span></div>
          </div>
          <!-- 举手 -->
          <div class="actionOne">
            <div class="actionTitle">举手</div>
            <div class="actionBar">
              <el-progress :percentage="Percent(actionData.handUp)" :stroke-width="20" :color="colorList[4]" />
            </div>
            <div class="actionNum"><span>{{ actionData.handUp }}</span><span>{{ Percent(actionData.handUp) }}%</span></div>
          </div>
          <!-- 站立 -->
          <div class="actionOne">
            <div class="actionTitle">站立</div>
            <div class="actionBar">
              <el-progress :percentage="Percent(actionData.stand)" :stroke-width="20" :color="colorList[5]" />
            </div>
            <div class="actionNum"><span>{{ actionData.stand }}</span><span>{{ Percent(actionData.stand) }}%</span></div>
          </div>
        </div>

        <div class="actionOnePart">
          <!-- 讨论 -->
          <div class="actionOne">
            <div class="actionTitle">讨论</div>
            <div class="actionBar">
              <el-progress :percentage="Percent(actionData.discuss)" :stroke-width="20" :color="colorList[6]" />
            </div>
            <div class="actionNum"><span>{{ actionData.discuss }}</span><span>{{ Percent(actionData.discuss) }}%</span></div>
          </div>
          <!-- 指导 -->
          <div class="actionOne">
            <div class="actionTitle">指导</div>
            <div class="actionBar">
              <el-progress :percentage="Percent(actionData.guid)" :stroke-width="20" :color="colorList[7]" />
            </div>
            <div class="actionNum"><span>{{ actionData.guid }}</span><span>{{ Percent(actionData.guid) }}%</span></div>
          </div>
          <!-- 睡觉 -->
          <div class="actionOne">
            <div class="actionTitle">睡觉</div>
            <div class="actionBar">
              <el-progress :percentage="Percent(actionData.sleep)" :stroke-width="20" :color="colorList[8]" />
            </div>
            <div class="actionNum"><span>{{ actionData.sleep }}</span><span>{{ Percent(actionData.sleep) }}%</span></div>
          </div>
          <!-- 使用手机 -->
          <div class="actionOne">
            <div class="actionTitle">使用手机</div>
            <div class="actionBar">
              <el-progress :percentage="Percent(actionData.phone)" :stroke-width="20" :color="colorList[9]" />
            </div>
            <div class="actionNum"><span>{{ actionData.phone }}</span><span>{{ Percent(actionData.phone) }}%</span></div>
          </div>
          <!-- 低头 -->
          <div class="actionOne">
            <div class="actionTitle">低头</div>
            <div class="actionBar">
              <el-progress :percentage="Percent(actionData.headDown)" :stroke-width="20" :color="colorList[10]" />
            </div>
            <div class="actionNum"><span>{{ actionData.headDown }}</span><span>{{ Percent(actionData.headDown) }}%</span></div>
          </div>
          <!-- 趴在桌子上 -->
          <div class="actionOne">
            <div class="actionTitle">趴在桌子上</div>
            <div class="actionBar">
              <el-progress :percentage="Percent(actionData.onTable)" :stroke-width="20" :color="colorList[11]" />
            </div>
            <div class="actionNum"><span>{{ actionData.onTable }}</span><span>{{ Percent(actionData.onTable) }}%</span></div>
          </div>
        </div>
      </div>
    </div>

    <div v-if="start" class="bottomDataLine" :class="{ 'showAttendance': !this.$ATTENDANCE }">
      <div class="bottomLabel">出<br>勤<br>率</div>
      <!-- 人头数统计 -->
      <div class="actionOne2">

        <div class="actionNum2"><span>实到{{ actualNumber }}人/应到{{ usersInfo.total }}人</span><span class="percent">{{ Percent(actualNumber) }}%</span></div>
        <div class="actionBar2">
          <el-progress :percentage="Percent(actualNumber)" :stroke-width="20" :color="colorList[12]" />
        </div>
        <div class="actionTitle2">人头数统计</div>

      </div>
      <!-- 精细化考勤 -->
      <div class="actionOne2">
        <div class="actionNum2"><span>识别{{ attendanceNumber }}人/共{{ usersInfo.total }}人</span><span class="percent">{{ Percent(attendanceNumber) }}%</span></div>
        <div class="actionBar2">
          <el-progress :percentage="Percent(attendanceNumber)" :stroke-width="20" :color="colorList[13]" />
        </div>
        <div class="actionTitle2">精细化考勤</div>

      </div>
      <!-- 按钮 -->
      <el-button type="primary" style="margin-right:20px" @click="checkPerson()">人脸考勤详情</el-button>
      <!-- 人脸考勤详情弹窗 -->
      <el-dialog title="人脸考勤详情" :visible.sync="facesDialog" width="80%" class="faceBox" @close="closeFaces()">
        <div class="openFrame">
          <div class="openFrame-left">
            <div class="openFrame-box-title">识别名单</div>
            <div class="openFrame-box" style="height:368px;margin-bottom:20px">
              <div v-for="(item,index) in recognized" :key="index" class="onePerson">
                <div class="onePerson-img"><img :src="photoUrl(item.photo)"></div>
                <div class="onePerson-name">{{ item.username }}</div>
              </div>
            </div>
            <div class="openFrame-box-title">未识别名单</div>
            <div class="openFrame-box" style="height:244px">
              <div v-for="item in noRecognized" :key="item.phone" class="onePerson">
                <div class="onePerson-img"><img :src="photoUrl(item.photo)"></div>
                <div class="onePerson-name">{{ item.username }}</div>
              </div>
            </div>
          </div>
          <div class="openFrame-right">
            <div class="right-one">
              <div>总人数：<span>{{ usersInfo.total }}</span></div>
              <div>实到人数：<span>{{ actualNumber }}</span></div>
              <div>识别人数：<span>{{ attendanceNumber }}</span></div>
            </div>
            <div class="right-two">
              <circleChart :data="dataA" :title="title1" :set="chartSet" />
            </div>
            <div class="right-two">
              <circleChart :data="dataB" :title="title2" :set="chartSet" />
            </div>

          </div>

        </div>
      </el-dialog>
    </div>

    <div v-else class="emptyBox">
      <img src="../../assets/defaultNo.png">
      课程已结束
      <el-button type="primary" @click="backToHome()">确 定</el-button>
    </div>

  </div>

</template>

<script>
import { getTaskRunning } from '@/api/main'
import { listUser } from '@/api/system/user'
import io from 'socket.io-client'
// 图表
import circleChart from './charts/circleChart.vue'
// 实时时间
import timePart from '../../components/time.vue'

export default {
  name: 'CurrentClass',
  components: { circleChart, timePart },
  data() {
    return {
      // total:45,
      className: null,
      taskName: null,
      imgsrc: require('../../assets/img001.png'),
      actionData: { // 0write书写 1read阅读 2listen听讲 3turn转头 4handUp举手 5stand站立 6discuss讨论 7guid指导 8sleep睡觉 9phone使用手机 10headDown低头 11onTable趴在桌子上
        // write:1,
        // read:2,
        // listen:3,
        // turn:4,
        // handUp:5,
        // stand:6,
        // discuss:7,
        // guid:8,
        // sleep:9,
        // phone:10,
        // headDown:11,
        // onTable:12
      },
      activeTab: 'student', // 默认激活学生标签
      isSwitching: false, // 添加切换状态标志
      playerInstance: null,
      videoSrc: '',
      // htmlSrc:'./webrtc/webrtc.html'
      testNum: 4,
      colorList: ['#34d6ff', '#34ffb0', '#bc6eff', '#8cff59', '#ffee34', '#34fffd', '#ffc350', '#ff865c', '#c3ff34', '#7ea5ff', '#fd93f9', '#66dbff', '#66ffb3', '#89ff71'],
      facesDialog: false,
      // 当前任务
      start: true,
      currentTask: {
        id: '',
        department_id: '',
        name: '',
        sampling_interval: null,
        videoStream1: null,
        videoStream2: null,
        start_time: null,
        duration: '2:00:0'
      },
      // 部门信息
      usersInfo: {
        items: [],
        total: null
      },
      // 考勤信息
      attendanceInfo: [],
      attendanceNumber: null,
      actualNumber: null,
      recognized: [], // 已识别出的人员list
      noRecognized: [], // 未识别名单
      title1: '出勤统计',
      title2: '识别统计',
      dataA: [],
      dataB: [],
      chartSet: {
        titleColor: '#333'
      }

    }
  },
  computed: {
    fullName() {
      return this.firstName + ' ' + this.lastName
    },

    Percent() {
      return (e) => {
        if (e > 0) {
          const num = e / this.usersInfo.total * 100
          return Number(num.toFixed(2))
        } else {
          return 0
        }
      }
    }
  },
  watch: {
    videoSrc(newVal) {
      if (newVal && newVal !== '') {
        this.startPlaying(newVal)
      } else if (this.playerInstance) {
        this.stopPlaying()
      }
    }
  },

  created() {
    console.log('--------------考勤', this.$ATTENDANCE)
    // this.runningTask()
    // websocket实时信息
    const _this = this
    const address = this.$API_BASE_URL + '/bhserver'
    this.socket = io(address, {
      transports: ['websocket']
    })
    this.socket.on('monitor_bh_data', function(data) {
      _this.actionData = { // 0书写 1阅读 2听讲 3转头 4举手 5站立 6讨论 7指导 8睡觉 9使用手机 10低头 11趴在桌子上
        write: data.behavior_data['0'],
        read: data.behavior_data['1'],
        listen: data.behavior_data['2'],
        turn: data.behavior_data['3'],
        handUp: data.behavior_data['4'],
        stand: data.behavior_data['5'],
        discuss: data.behavior_data['6'],
        guid: data.behavior_data['7'],
        sleep: data.behavior_data['8'],
        phone: data.behavior_data['9'],
        headDown: data.behavior_data['10'],
        onTable: data.behavior_data['11']
      }
      _this.attendanceInfo = data.attendance_data
      // _this.attendanceNumber = data.attendance_data.length - 1
      _this.actualNumber = data.attendance_data[0]
      // 识别出的人员数
      if (data.attendance_data.length === 2 && data.attendance_data[1] === '') {
        _this.attendanceNumber = 0
      } else {
        _this.attendanceNumber = data.attendance_data.length - 1
      }
      // console.log('-------------', data.behavior_data)

      // _this.actionData = {'2':0,'3':1}
      // _this.testNum=5
    })
    _this.startPlaying()
  },

  mounted() {
    this.$nextTick(() => {
      console.log('视频元素ref状态:', this.$refs.player)
      this.startPlaying()
    })
  },
  beforeDestroy() {
    console.log('销毁前播放器状态:', this.playerInstance)
    
    // 1. 优先停止播放器
    if (this.playerInstance) {
      this.stopPlaying()
    }
    
    // 2. 强制清理视频元素（防止内存泄漏）
    const videoElement = this.$refs.player
    if (videoElement) {
      videoElement.srcObject = null
      videoElement.removeAttribute('src')
      videoElement.load()
    }
    
    // 3. 关闭socket
    if (this.socket) {
      this.socket.close()
    }
  },

  methods: {
    // 正在进行的任务
    runningTask() {
      getTaskRunning().then(response => {
        if (!response.data) {
          this.start = false
        } else {
          this.start = true
          this.currentTask = response.data.task_data
          this.className = response.data.department.name
          this.taskName = response.data.task_data.name
          console.log('----------正在进行的任务', this.currentTask)
          const param = {
            page: 1,
            limit: 1000,
            deptId: response.data.department_id
          }
          this.getDepInfo(param)
        }
      })
    },
    // 通过部门id获取信息
    getDepInfo(param) {
      listUser(param).then(response => {
        this.usersInfo = response.data
        console.log('----------通过部门id获取信息', this.usersInfo)
      })
    },
    // 关闭人脸识别详情
    closeFaces() {
      this.facesDialog = false
      this.recognized = []
      this.noRecognized = []
    },

    // 返回上一级
    back() {
      this.$router.back()
    },
    // 返回主页
    backToHome() {
      this.$router.push({ path: '/startClass' })
    },
    // 精细化考勤弹窗
    checkPerson() {
      this.facesDialog = true
      // 筛选赋值
      // A已识别出的人的id---this.attendanceInfo
      // B所有人员---this.usersInfo
      var arr1 = this.usersInfo.items
      var arr2 = this.attendanceInfo

      for (var i = 0; i < arr1.length; i++) {
        var id1 = arr1[i].id
        // var isDifferent = false;
        for (var j = 0; j < arr2.length; j++) {
          var id2 = arr2[j]
          if (id1 === Number(id2)) {
            this.recognized.push(arr1[i]) // 这是相同的值
            break
          }
        }
      }
      // 从所有人员总减去已识别出来的人
      // 从arr1中减去arr2中包含的元素
      this.noRecognized = arr1.filter(item => !this.recognized.includes(item))

      // 传递图表数据
      const tatalNum = this.usersInfo.total// 总人数
      const actualNum = this.actualNumber// 实到人数
      const actualNumNone = tatalNum - actualNum// 未到人数
      const attentNum = this.attendanceNumber// 识别人数
      const attentNumNone = tatalNum - attentNum// 未识别人数
      // console.log('-----总人数', tatalNum)
      // console.log('-----实到人数', actualNum)
      // console.log('-----未到人数', actualNumNone)
      // 出勤率
      this.dataA = [
        { value: actualNum, name: '出勤数' },
        { value: actualNumNone, name: '缺勤数' }
      ]
      // 识别率
      this.dataB = [
        { value: attentNum, name: '识别数' },
        { value: attentNumNone, name: '未识别' }
      ]
    },
    photoUrl(e) {
      return this.$API_BASE_URL + '/upload/' + e
    },
    // 关于播放器的代码
    // 切换标签
    switchTab(tab) {
      if (this.activeTab === tab || this.isSwitching) return;
      this.isSwitching = true;
      this.activeTab = tab;

      // 强制销毁旧实例，确保资源释放
      this.stopPlaying();

      // 等待 DOM 更新完成后再初始化新播放器
      this.$nextTick(() => {
        this.startPlaying();
        this.isSwitching = false;
      });
    },

    startPlaying() {
      this.runningTask();

      const videoElement = this.$refs.player;
      if (!videoElement) {
        console.error('错误：视频元素未找到！');
        return;
      }

      const streamType = this.activeTab === 'student' ? 'student' : 'teacher';
      const url = `${this.$WEBRTC_URL}/live/${streamType}`;
      console.log('当前视频流 URL:', url);

      try {
        // eslint-disable-next-line no-undef
        this.playerInstance = new JSWebrtc.Player(url, {
          video: videoElement,
          autoplay: true,
          muted: true, // 静音以绕过自动播放限制
          onplay: () => {
            console.log('播放成功');
            this.isSwitching = false;
          },
          onerror: (err) => {
            console.error('播放失败:', err);
            this.isSwitching = false;
          }
        });
      } catch (error) {
        console.error('播放器初始化失败:', error);
        this.isSwitching = false;
      }
    },
    // 停止
    stopPlaying() {
      if (this.playerInstance) {
        try {
          // 1. 调用播放器的销毁方法
          this.playerInstance.destroy();
          // 2. 手动清理视频元素
          const videoElement = this.$refs.player;
          if (videoElement) {
            videoElement.srcObject = null;
            videoElement.removeAttribute('src');
            videoElement.load(); // 重置视频元素
          }
        } catch (error) {
          console.error('停止播放失败:', error);
        } finally {
          this.playerInstance = null;
        }
      }
    }
  }
}
</script>

<style scoped>
.mainPart{
  height: calc((100vh - 117px) * 7 / 10 );
  padding-right: 20px;
}
.videoPart{
  height: calc((100vh - 117px) * 7 / 10 );
  width: calc((100vh - 117px) * 7 / 10 * 16 / 9) ;
}
.mainPart2{
  height: calc((100vh - 117px) * 8 / 10 );
  padding-right: 20px;
  margin-top: calc((100vh - 117px) * 1 / 15 );
}
.videoPart2{
  height: calc((100vh - 117px) * 8 / 10 );
  width: calc((100vh - 117px) * 8 / 10 * 16 / 9) ;
}
.actionData{
  padding:0;
  flex-direction: row;
}
.actionTitle{
  font-size: 18px;
}
.actionBar{
  height: 20px;
}
.actionNum{
  font-size: 16px;
}
.showAttendance{
  display: none;
}
</style>

